package info

import (
	"encoding/json"
	"fmt"
	"os/exec"

	"gitee.com/shiwjlinux/gserror/common"
)

// 定义结构体
type AgentInfo struct {
	PaasURL  string `json:"paasurl"`
	GsdID    string `json:"gsdid"`
	AgentVer string `json:"agent_ver"`
	GS       []*GS  `json:"gs"`
}

type GS struct {
	GSID   string `json:"gsid"`
	GSVer  string `json:"gs_ver"`
	Status string `json:"status"`
	Cause  string `json:"cause"`
}

func (a *AgentInfo) String() string {
	b, _ := json.Marshal(a)
	return string(b)
}

func (g *GS) String() string {
	b, _ := json.Marshal(g)
	return string(b)
}

func (g *GS) StatusError() *GS {
	if g == nil {
		return nil
	}
	if g.Status == STATUS_ERROR {
		return g
	}
	return nil
}

func (g *GS) Kill() error {
	// TODO: kill gs
	// root          1277 28734 0 11:32:27 ?     00:28:25 wl-arm-gs --gsdid=1001010000103456 --gsid=100101000010345601 --port=9000 --agent_ip=10.4.0.1 --net_logger_url=http://172.16.1.188:13000/log/log_arm_gs
	fmt.Printf("%s gs %s status is %s: %s, killing ...\n", common.NowTime(), g.GSID, g.Status, g.Cause)

	cmd := exec.Command("pkill", "-f", g.GSID) // This command filters by g.GSID
	return cmd.Run()
}

func NewGS() *GS {
	return &GS{}
}

func NewAgentInfo() *AgentInfo {
	return &AgentInfo{
		GS: make([]*GS, 0),
	}
}
